<template>
  <div class="monitor-alerts">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>监控告警</span>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="refreshAlerts">刷新</el-button>
            <el-button size="small" @click="viewAllAlerts">查看全部告警</el-button>
          </div>
        </div>
      </template>

      <!-- 告警统计 -->
      <div class="alert-stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-item">
                <div class="stat-value critical">{{ alertStats.critical }}</div>
                <div class="stat-label">严重告警</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-item">
                <div class="stat-value high">{{ alertStats.high }}</div>
                <div class="stat-label">高级告警</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-item">
                <div class="stat-value medium">{{ alertStats.medium }}</div>
                <div class="stat-label">中级告警</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-item">
                <div class="stat-value low">{{ alertStats.low }}</div>
                <div class="stat-label">低级告警</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 告警列表 -->
      <el-table :data="alerts" style="width: 100%" v-loading="loading">
        <el-table-column prop="time" label="时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.time) }}
          </template>
        </el-table-column>
        <el-table-column prop="layer" label="数据层" width="100">
          <template #default="{ row }">
            <el-tag :type="getLayerTagType(row.layer)" size="small">
              {{ row.layer }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="table_name" label="表名" />
        <el-table-column prop="alert_type" label="告警类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getAlertTypeColor(row.alert_type)" size="small">
              {{ getAlertTypeText(row.alert_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="severity" label="严重程度" width="100">
          <template #default="{ row }">
            <el-tag :type="getSeverityType(row.severity)" size="small">
              {{ getSeverityText(row.severity) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="message" label="告警信息" show-overflow-tooltip />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="viewAlertDetail(row)">
              详情
            </el-button>
            <el-button 
              v-if="row.status === 'active'" 
              type="text" 
              size="small" 
              @click="acknowledgeAlert(row)"
            >
              确认
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { alertApi } from '@/api/alert'

const router = useRouter()

// 告警数据
const alerts = ref<any[]>([])
const loading = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 告警统计
const alertStats = computed(() => {
  const stats = {
    critical: 0,
    high: 0,
    medium: 0,
    low: 0
  }
  
  alerts.value.forEach(alert => {
    switch (alert.severity) {
      case 'critical':
        stats.critical++
        break
      case 'high':
        stats.high++
        break
      case 'medium':
        stats.medium++
        break
      case 'low':
        stats.low++
        break
    }
  })
  
  return stats
})

// 加载告警数据
const loadAlerts = async () => {
  loading.value = true
  try {
    const response = await alertApi.getHistory({
      page: pagination.page,
      size: pagination.size
    })
    alerts.value = response.data.items
    pagination.total = response.data.pagination.total
  } catch (error) {
    console.error('Failed to load alerts:', error)
    ElMessage.error('加载告警数据失败')
  } finally {
    loading.value = false
  }
}

// 刷新告警
const refreshAlerts = () => {
  loadAlerts()
}

// 查看全部告警
const viewAllAlerts = () => {
  router.push('/alert/history')
}

// 查看告警详情
const viewAlertDetail = (alert: any) => {
  router.push(`/alert/detail/${alert.id}`)
}

// 确认告警
const acknowledgeAlert = async (alert: any) => {
  try {
    // 模拟确认告警，实际项目中应该调用真实API
    ElMessage.success('告警已确认')
    // 更新告警状态
    alert.status = 'acknowledged'
  } catch (error) {
    console.error('Failed to acknowledge alert:', error)
    ElMessage.error('确认告警失败')
  }
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadAlerts()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadAlerts()
}

// 工具函数
const formatTime = (time: string): string => {
  return new Date(time).toLocaleString('zh-CN')
}

const getLayerTagType = (layer: string): string => {
  const types: Record<string, string> = {
    'TDS': 'success',
    'ODS': 'warning',
    'DWD': 'primary',
    'DWS': 'info',
    'DIM': 'danger',
    'ADS': 'success'
  }
  return types[layer] || 'info'
}

const getAlertTypeColor = (type: string): string => {
  const colors: Record<string, string> = {
    'data_volume': 'warning',
    'data_quality': 'danger',
    'performance': 'info',
    'custom': 'primary'
  }
  return colors[type] || 'info'
}

const getAlertTypeText = (type: string): string => {
  const texts: Record<string, string> = {
    'data_volume': '数据量异常',
    'data_quality': '数据质量',
    'performance': '性能异常',
    'custom': '自定义'
  }
  return texts[type] || type
}

const getSeverityType = (severity: string): string => {
  const types: Record<string, string> = {
    'low': 'info',
    'medium': 'warning',
    'high': 'danger',
    'critical': 'danger'
  }
  return types[severity] || 'info'
}

const getSeverityText = (severity: string): string => {
  const texts: Record<string, string> = {
    'low': '低',
    'medium': '中',
    'high': '高',
    'critical': '严重'
  }
  return texts[severity] || severity
}

const getStatusType = (status: string): string => {
  const types: Record<string, string> = {
    'active': 'danger',
    'acknowledged': 'warning',
    'resolved': 'success',
    'closed': 'info'
  }
  return types[status] || 'info'
}

const getStatusText = (status: string): string => {
  const texts: Record<string, string> = {
    'active': '活跃',
    'acknowledged': '已确认',
    'resolved': '已解决',
    'closed': '已关闭'
  }
  return texts[status] || status
}

onMounted(() => {
  loadAlerts()
})
</script>

<style scoped>
.monitor-alerts {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.alert-stats {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-value.critical {
  color: #F56C6C;
}

.stat-value.high {
  color: #E6A23C;
}

.stat-value.medium {
  color: #409EFF;
}

.stat-value.low {
  color: #67C23A;
}

.stat-label {
  color: #606266;
  font-size: 14px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}
</style> 